package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.code.BusinessEnum;
import com.qk.code.ParamEnum;
import com.qk.exception.BusinessException;
import com.qk.management.annotation.LogAnno;
import com.qk.management.mapper.RoleMapper;
import com.qk.properties.JwtProperties;
import com.qk.result.PageResult;
import com.qk.dto.user.UserDTO;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.util.JwtUtils;
import com.qk.vo.common.LoginResultVO;
import com.qk.vo.user.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Author:zhengbowen
 * @Date: 2025/10/06 19:28
 * @Description: 用户管理业务逻辑
 */
@Service
@Slf4j
@RequiredArgsConstructor
@EnableConfigurationProperties(JwtProperties.class)
public class UserServiceImpl implements UserService {

    public final UserMapper userMapper;
    public final RoleMapper roleMapper;
    private final JwtProperties jwtProperties;

    @Override
    public PageResult<UserVO> selectUsersByPage(UserDTO userDto) {
        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());
        List<UserVO> userVOList = userMapper.selectUsersByPage(userDto);
        userVOList.forEach(user -> user.setPhone(DesensitizedUtil.mobilePhone(user.getPhone())));
        PageInfo<UserVO> pageInfo = new PageInfo<>(userVOList);
        return PageResult.<UserVO>builder()
                .total(pageInfo.getTotal())
                .rows(pageInfo.getList())
                .build();
    }
    @Override
    public List<User> selectUserList() {
        return userMapper.selectUserList();
    }

    @Override
    public User selectUserById(String id) {

        return userMapper.selectUserById(id);
    }

    @Override
    @LogAnno
    public void addUser(User user) {
        if(BeanUtil.hasNullField(user, "id","remark","createTime","updateTime","password","image")){
            throw new BusinessException(ParamEnum.PARAM_ERROR);
        }
        User user1 = userMapper.selectUserByUsername(user.getUsername());
        if (user1 != null) {
            throw new BusinessException(BusinessEnum.USER_NOT_FOUND);
        }
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+"123").getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insertData(user);
    }

    @Override
    public List<User> selectUserByRoleLabel(String roleLabel) {

        return userMapper.selectUserByRoleLabel(roleLabel);
    }

    @Override
    public List<User> selectUserByDeptId(Integer deptId) {

        return userMapper.selectUserByDeptId(deptId);
    }

    @Override
    @LogAnno
    public void deleteUsers(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    @LogAnno
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(user);
    }

    @Override
    public LoginResultVO login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user == null || !user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            throw new BusinessException(BusinessEnum.USER_PASSWORD_ERROR);
        }

        if (user.getStatus()==0) {
            throw new BusinessException(BusinessEnum.USER_STATUS_ERROR);
        }
        String roleLabel = roleMapper.selectRoleLabelByRoleId(user.getRoleId());
        LoginResultVO loginResult = new LoginResultVO();
        BeanUtil.copyProperties(user, loginResult);
        loginResult.setRoleLabel(roleLabel);
        Map<String, Object> claims = BeanUtil.beanToMap(loginResult);
        String jwt = JwtUtils.createJwt(jwtProperties.getSecretKey(), jwtProperties.getTtlMillis(),claims);
        loginResult.setToken(jwt);
        return loginResult;
    }
}
